# -*- coding: utf-8 -*-
import json


def json_r():
    try:
        with open("员工信息.json", "r", encoding="utf-8") as f:
            data = json.load(f)
            return data
    except Exception as esc:
        print(esc)


def json_w(new_name, new_emp):
    data = json_r()
    with open('员工信息.json', 'w', encoding='utf8') as f:
        if data is not None:
            data[new_name] = new_emp
        else:
            data = {new_name: new_emp}
        json.dump(data, f)


def submit(data):
    with open('员工信息.json', 'w') as f:
        json.dump(data, f)


def add_emp():
    name = input('输入新员工姓名：')
    tel = input('输入新员工电话：')
    job = input('输入新员工职位：')
    new_emp = {
        'months': [0] * 12,
        'other': {
            'job': job,
            'tel': tel
        }}
    json_w(name, new_emp)


def updata():
    name = input('你要为哪位员工修改考勤：')
    month = int(input('修改几月份考勤：'))
    days = int(input('将改月考勤修改为多少天：'))
    data = json_r()
    data[name]['months'][month - 1] = days
    submit(data)


def del_emp():
    name = input('你要删除哪位员工：')
    data = json_r()
    try:
        data.pop(name)
    except KeyError:
        print('该员工不存在！')
    submit(data)


def all_name():
    data = json_r()
    print(data.keys())


def sel_msg():
    try:
        name = input('你要查找哪位员工信息：')
        data = json_r()
        print(data[name])
    except KeyError:
        print('该员工不存在！')


def emp_mange():
    act = int(input('选择你要进行的操作：（1）添加新员工（2）更新员工考勤（3）删除员工信息（4）获取员工列表（5）查找员工信息（6）退出'))
    if act == 1:
        add_emp()
        emp_mange()
    elif act == 2:
        updata()
        emp_mange()
    elif act == 3:
        del_emp()
        emp_mange()
    elif act == 4:
        all_name()
        emp_mange()
    elif act == 5:
        sel_msg()
        emp_mange()
    elif act == 6:
        return
    else:
        print('请检查输入内容！')


if __name__ == '__main__':
    emp_mange()

"""
# 验证文件读写嵌套：w模式会清空文件，不可内置读
def temp():
    with open('员工信息.json', 'r', encoding='utf8') as f:
        with open('员工信息.json', 'w', encoding='utf8') as f1:
            data = {'temp1': {
                'months': [0] * 12,
                'other': {
                    'job': 'boss',
                    'tel': '1241243143'
                }}}
            json.dump(data, f1)
        print(json.load(f))
"""
